package db

import (
	"gitee.com/daka1004/devops-runner/models"
	"github.com/glebarez/sqlite"
	"gorm.io/gorm"
)

var db *gorm.DB

func InitDB() {
	var err error
	db, err = gorm.Open(sqlite.Open("sqlite3/runners.db"), &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}
	db.AutoMigrate(&models.Task{})
}

func CreateTask(task *models.Task) error {
	return db.Create(task).Error
}

func IsTaskExists(task *models.Task) (bool, error) {
	var count int64
	err := db.Model(&models.Task{}).Where("serial =?", task.Serial).Count(&count).Error
	if err != nil {
		return false, err
	}
	return count > 0, nil
}
func SelectTask(task *models.Task) (models.Task, error) {
	entity := models.Task{}
	first := db.Model(&models.Task{}).Where("serial =?", task.Serial).First(entity)
	err := first
	if err != nil {
		return models.Task{}, nil
	}
	return entity, nil
}
